package com.vehicle.biz.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.vehicle.biz.SysUserBiz;
import com.vehicle.domains.entity.SysRoleEntity;
import com.vehicle.domains.entity.SysUserEntity;
import com.vehicle.domains.entity.SysUserRoleEntity;
import com.vehicle.domains.info.UserInfo;
import com.vehicle.domains.vo.BasePage;
import com.vehicle.domains.bo.QueryRoleBo;
import com.vehicle.domains.bo.QueryUserBo;
import com.vehicle.domains.vo.req.sysUser.*;
import com.vehicle.domains.vo.res.sysPermission.SysPermissionRes;
import com.vehicle.domains.vo.res.sysRole.SysRoleRes;
import com.vehicle.domains.vo.res.sysUser.SysUserRes;
import com.vehicle.enums.ActiveEnum;
import com.vehicle.exception.VehicleAccessException;
import com.vehicle.service.SysRoleService;
import com.vehicle.service.SysUserRoleService;
import com.vehicle.service.SysUserService;
import com.vehicle.service.config.SystemConfig;
import com.vehicle.service.config.SystemConfigService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SysUserBizImpl implements SysUserBiz {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SystemConfigService systemConfigService;

    @Override
    public void addUser(AddUserReq user) {
        SysUserEntity userEntity = sysUserService.selectByUsername(user.getUsername());
        if (userEntity != null) {
            throw VehicleAccessException.DATA_EXIST.newInstance("用户已存在");
        }
        SysUserEntity sysUserEntity = new SysUserEntity();
        BeanUtils.copyProperties(user, sysUserEntity);
        sysUserEntity.setPassword(systemConfigService.get(SystemConfig.defaultPassword));
        sysUserService.addUser(sysUserEntity);
    }

    @Override
    public void updateUser(UpdateUserReq req) {
        checkUserExist(req.getId());
        SysUserEntity updateSysUser = new SysUserEntity();
        BeanUtils.copyProperties(req, updateSysUser);
        sysUserService.updateUser(updateSysUser);
    }

    @Override
    public void deleteUser(Long id) {
        checkUserExist(id);
        sysUserService.deleteUser(id);
    }

    @Override
    public SysUserRes getUserById(Long id) {
        SysUserEntity sysUserEntity = checkUserExist(id);
        SysUserRes sysUserRes = new SysUserRes();
        BeanUtils.copyProperties(sysUserEntity, sysUserRes);
        String password = DesensitizedUtil.password(sysUserRes.getPassword());
        sysUserRes.setPassword(password);
        return sysUserRes;
    }

    @Override
    public BasePage<SysUserRes> selectUserList(ListUserReq req) {
        Page<SysUserEntity> page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        QueryUserBo queryUserBo = new QueryUserBo();
        BeanUtils.copyProperties(req, queryUserBo);
        List<SysUserEntity> sysUserEntityList= sysUserService.selectUserList(queryUserBo);
        List<SysUserRes> sysUserResList = sysUserEntityList.stream().map(sysUserEntity -> {
            SysUserRes sysUserRes = new SysUserRes();
            BeanUtils.copyProperties(sysUserEntity, sysUserRes);
            String password = DesensitizedUtil.password(sysUserRes.getPassword());
            sysUserRes.setPassword(password);
            return sysUserRes;
        }).toList();
        return BasePage.generateResult(page.getTotal(), page.getPages(), sysUserResList);
    }

    @Override
    public void addUserRoles(AddUserRolesReq req) {
        Long userId = req.getUserId();
        //判断用户是否存在
        checkUserExist(userId);
        if (CollectionUtil.isEmpty(req.getRoleIds())) {
            sysUserRoleService.addUserRoles(userId,null);
            return;
        }

        QueryRoleBo queryRoleBo = new QueryRoleBo();
        queryRoleBo.setIds(req.getRoleIds());
        queryRoleBo.setStatusList(Collections.singletonList(ActiveEnum.ACTIVE.name()));

        //检验角色合法性
        List<SysRoleEntity> sysRoleEntityList = sysRoleService.selectRoleList(queryRoleBo);
        if (CollectionUtil.isEmpty(sysRoleEntityList) || sysRoleEntityList.size() != req.getRoleIds().size()) {
            throw VehicleAccessException.DATA_NOT_EXIST.newInstance("有角色id不存在");
        }

        List<SysUserRoleEntity> list = new ArrayList<>();

        for (SysRoleEntity sysRoleEntity : sysRoleEntityList) {
            SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
            sysUserRoleEntity.setUserId(userId);
            sysUserRoleEntity.setRoleId(sysRoleEntity.getId());
            list.add(sysUserRoleEntity);
        }

        //删除老的用户角色，添加新的用户角色
        sysUserRoleService.addUserRoles(userId,list);

    }

    @Override
    public SysUserRes login(UserLoginReq req) {
        SysUserRes sysUserRes = new SysUserRes();
        SysUserEntity sysUserEntity = sysUserService.selectByUsername(req.getUsername());
        if (sysUserEntity==null){
            throw VehicleAccessException.DATA_NOT_EXIST.newInstance("用户不存在");
        }
        if (!sysUserEntity.getPassword().equals(req.getPassword())){
            throw VehicleAccessException.DATA_NOT_EXIST.newInstance("密码错误");
        }

        String token = generateToken(req.getUsername(), sysUserEntity.getId());
        sysUserRes.setToken(token);

        UserInfo userInfo =sysUserService.getUserRoleAndPermission(sysUserEntity.getId());

        List<SysRoleRes> sysRoleResList = userInfo.getRoleEntityList().stream().map(sysRoleEntity -> {
            SysRoleRes sysRoleRes = new SysRoleRes();
            BeanUtils.copyProperties(sysRoleEntity, sysRoleRes);
            return sysRoleRes;
        }).toList();
        sysUserRes.setRoleResList(sysRoleResList);

        List<SysPermissionRes> sysPermissionResList = userInfo.getPermissionEntityList().stream().map(sysPermissionEntity -> {
            SysPermissionRes sysPermissionRes = new SysPermissionRes();
            BeanUtils.copyProperties(sysPermissionEntity, sysPermissionRes);
            return sysPermissionRes;
        }).toList();
        sysUserRes.setPermissionResList(sysPermissionResList);

        BeanUtils.copyProperties(sysUserEntity, sysUserRes);
        sysUserRes.setPassword(DesensitizedUtil.password(sysUserRes.getPassword()));
        return sysUserRes;
    }

    private String generateToken(String username, Long id) {
        JWTSigner jwtSigner = JWTSignerUtil.hs256(systemConfigService.get(SystemConfig.jwtSecurityKey).getBytes());
        return JWT.create()
                .setPayload("username", username)
                .setPayload("userId", id)
                .setExpiresAt(new Date(System.currentTimeMillis()+systemConfigService.get(SystemConfig.jwtTokenExpireTime)))
                .sign(jwtSigner);
    }

    private SysUserEntity checkUserExist(Long id) {
        SysUserEntity sysUserEntity=sysUserService.selectByUserId(id);
        if (sysUserEntity==null){
            throw VehicleAccessException.DATA_NOT_EXIST.newInstance("用户不存在");
        }
        return sysUserEntity;
    }
}
